package com.bdqn.t382.lx;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;

import java.util.Random;

@Aspect
public class PrinterAspect {
    // 定义切入点，匹配 Printer 的 print 方法
    @Pointcut("execution(* com.bdqn.t382.lx.Printer1.print(..))")
    public void printMethod() {
    }

    // 前置增强：在打印前进行自检
    @Before("printMethod()")
    public void beforePrint(JoinPoint joinPoint) {
        Random random = new Random();
        int checkResult = random.nextInt(10); // 生成 0-9 的随机数
        if (checkResult >= 5) {
            throw new RuntimeException("打印机自检失败，无法打印！");
        } else {
            System.out.println("打印机自检正常，可以继续打印。");
        }
    }

    // 后置增强：打印成功后记录日志
    @AfterReturning(pointcut = "printMethod()", returning = "retVal")
    public void afterPrint(Object retVal) {
        System.out.println("打印成功，内容已输出。");
    }

    // 异常抛出增强：捕获并打印异常信息
    @AfterThrowing(pointcut = "printMethod()", throwing = "ex")
    public void afterThrowing(Throwable ex) {
        System.out.println("打印过程中出现异常：" + ex.getMessage());
    }
}
